/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snail.task;

import com.snail.beans.CmdResult;
import com.snail.main.XTask;
import it.sauronsoftware.cron4j.TaskExecutionContext;
import org.jsoup.nodes.Element;

/**
 *
 * @author pm
 */
public class PingTask extends XTask {

    public PingTask(Element full_cfg, Element cfg, Element module) {
        super(full_cfg, cfg, module);
    }

    @Override
    public void onExecute(TaskExecutionContext tec) throws RuntimeException {
        Element ping = cfg.select(">ping").first();
        if (cfg.select(">success").size() > 0) {
            String host = ping.attr("host");
            String intval = ping.attr("intval");
            String count = ping.attr("count");
            String ping_cmd = "ping -n -c " + count + " -i" + intval + " " + host;
            CmdResult result = exec(ping_cmd, 0);
            String output = result.getOutput();
            if (result.isSuccess()) {
                if (!output.contains("unknown host")) {
                    String strs[] = output.split("\n");
                    if (strs[strs.length - 1].startsWith("rtt")) {
                        int min_success_count = Integer.parseInt(cfg.select(">success").attr("min-success-count"));
                        int max_avg_time = Integer.parseInt(cfg.select(">success").attr("max-avg-time"));
                        //成功
                        String info = strs[strs.length - 2];
                        String rtt = strs[strs.length - 1];
                        int okay_count = Integer.parseInt(info.split(" ")[3]);
                        int avg = (int) Math.ceil(Float.parseFloat(rtt.split("/")[4]));
                        boolean isSuccess = okay_count >= min_success_count && ((max_avg_time > 0 && avg <= max_avg_time) || max_avg_time == 0);
                        if(isSuccess){
                            onSuccess("");
                        }else{
                            onError("1", "");
                        }
                    } else {
                        //超时,主机不在线
                        onError("5", "");
                    }
                } else {
                    //地址不存在
                    onError("4", "");
                }
            } else {
                //命令执行失败
                onError("2", "");
            }
        }

    }
}
